<!--
@Descripttion 文件上传
@version 1.0.0
@Author Bell
@ 使用
  引入组件
    import FUpload from '@/components/form/f-upload'
  注册组件
    components: {
      FUpload
    }
  使用
    <FUpload v-model.trim="xxx" />
    <FUpload v-model.trim="xxx" urlName="" ：limit="{size:5,sizeType:'MB'}" accept="" :disabled="false" />
    urlName  String  默认值('')                     文件url
    limit    String  默认值({size:5,sizeType:'MB'}) 文件大小限制
    accept   String  默认值('')                     上传类型 // .png,.jpg,.jpeg,.bmp,.gif  .doc,.docx  .xls,.xlsx  .ppt,.pptx  .zip,.rar
    disabled Boolean 默认值(false)                  是否失效
 -->
<template>
  <div class="uploader-box">
    <el-upload
      action="/api/order/upload/upload"
      :before-upload="beforeUpload"
      :on-success="avatarSuccess"
      :on-error="avatarError"
      :accept="accept"
      :headers="headers"
      :show-file-list="false"
      class="avatar-uploader"
    >
      <div v-loading="loading">
        <template v-if="imgUrl">
          <div class="img-box">
            <el-image :src="imgUrl" fit="contain"></el-image>
          </div>
          <span class="show-icon">
            <i v-if="type === 'img'" class="el-icon-view" @click.stop="preview()"></i>
            <i v-else class="el-icon-download" @click.stop="download()"></i>
            <i class="el-icon-delete" @click.stop="remove()"></i>
          </span>
        </template>
        <template v-else>
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </template>
      </div>
    </el-upload>
    <!--预览图片-->
    <PreviewImage :win="previewImageWin" />
  </div>
</template>

<script>
import PreviewImage from '@/components/dialog/preview-image'

export default {
  components: { PreviewImage },
  name: 'f-upload',
  model: {
    prop: 'urlName',
    event: 'change'
  },
  props: {
    // 文件url
    urlName: {
      type: String,
      default: ''
    },
    // 文件大小限制
    limit: {
      type: Object,
      default() {
        return {
          size: 5, // 大小
          sizeType: 'MB' // 大小类型 MB, KB
        }
      }
    },
    // 上传类型
    // .png,.jpg,.jpeg,.bmp,.gif
    // .doc,.docx
    // .xls,.xlsx
    // .ppt,.pptx
    // .zip,.rar
    accept: {
      type: String,
      default: ''
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      type: null, // 文件类型
      headers: {}, // 请求头
      imgUrl: null, // 图片地址
      loading: false, // 是否上传中
      // 预览图片弹框
      previewImageWin: {
        show: false,
        url: ''
      }
    }
  },
  mounted() {
    this.headers.Authorization = this.$store.getters.GET_TOKEN
  },
  watch: {
    urlName: {
      handler(newValue, oldValue) {
        if (newValue) {
          // 获取文件类型
          this.type = this.getFileObject(newValue)
          // 根据文件类型展示预览图片或者内置文件图标
          if (this.type === 'img') {
            this.imgUrl = newValue
          } else {
            this.imgUrl = require(`@/assets/images/upload-file/${this.type}.png`)
          }
        } else {
          this.imgUrl = null
        }
      },
      immediate: true
    }
  },
  methods: {
    /**
     * 图片预览
     */
    preview() {
      this.previewImageWin.show = true
      this.previewImageWin.url = this.imgUrl
    },
    /**
     * 下载
     */
    download() {
      window.open(this.urlName)
    },
    /**
     * 删除
     */
    remove() {
      // 页面删除
      this.$emit('change', null)
    },
    /**
     * 上传成功
     * @param {Object} res
     * @param {Object} file
     */
    avatarSuccess(res, file) {
      this.loading = false
      if (res.code === 0) {
        // 返回url
        this.$emit('change', res.data.url)
      } else {
        this.$message.error(res.message)
      }
    },
    /**
     * 文件上传失败
     */
    avatarError() {
      this.loading = false
      this.$message.error(this.$t('message.Upload failed please try again later'))
    },
    /**
     * 上传前 验证大小
     * @param {Object} file
     */
    beforeUpload(file) {
      let isSize = false // 文件大小限制
      // 验证文件大小
      if (this.limit.sizeType === 'KB') {
        isSize = file.size / 1024 < this.limit.size
      } else {
        isSize = file.size / 1024 / 1024 < this.limit.size
      }
      if (!isSize) {
        this.$message.warning(`${this.$t('message.FileSize cannot exceed')}${this.limit.size}${this.limit.sizeType}!`)
        return false
      }
      this.loading = true
      return true
    },
    /**
     * 获取文件类型
     * @param {Object} fileName
     */
    getFileObject(fileName) {
      const flieArr = fileName.split('.')
      const suffix = flieArr[flieArr.length - 1]
      const excelist = ['xls', 'xlsx']
      const wordlist = ['doc', 'docx']
      const pdflist = ['pdf']
      const imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif']
      if (excelist.some((item) => {
        return item === suffix
      })) {
        return 'ecel'
      }
      if (wordlist.some((item) => {
        return item === suffix
      })) {
        return 'word'
      }
      if (pdflist.some((item) => {
        return item === suffix
      })) {
        return 'pdf'
      }
      if (imglist.some((item) => {
        return item === suffix
      })) {
        return 'img'
      }
      return 'file'
    }
  }
}
</script>

<style lang="less" scoped>
.uploader-box {
  display: inline-block;
}
.img-box {
  display: block;
  width: 108px;
  height: 72px;
  &>.el-image{
    width: 100%;
    height: 100%;
  }
}
.show-icon {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  cursor: default;
  text-align: center;
  color: #fff;
  opacity: 0;
  font-size: 20px;
  background-color: rgba(0, 0, 0, 0.5);
  transition: opacity 0.3s;
  &:hover {
    opacity: 1;
  }
  &:after {
    display: inline-block;
    content: '';
    height: 100%;
    vertical-align: middle;
  }
  > i {
    cursor: pointer;
    &:not(:last-child) {
      margin-right: 8px;
    }
  }
}
.avatar-uploader {
  /deep/ .el-upload {
    border: 1px dashed #d1c3c0;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #d1c3c0;
    width: 108px;
    height: 72px;
    line-height: 76px;
    text-align: center;
  }
}
</style>
